package xcrypto

import (
	"crypto/aes"
	"crypto/cipher"

	"gitee.com/lihaiping1603/utils/log"
)

func Encrypt(plaintext, key, iv []byte) ([]byte, error) {
	// 创建加密算法 aes
	c, err := aes.NewCipher(key)
	if err != nil {
		log.Error("NewCipher(%d bytes) error:%s", len(key), err)
		return nil, err
	}

	// 加密字符串
	cfbenc := cipher.NewCFBEncrypter(c, iv)
	//存储密文用的
	ciphertext := make([]byte, len(plaintext))
	cfbenc.XORKeyStream(ciphertext, plaintext)
	log.Info("%s=>%x\n", plaintext, ciphertext)
	return ciphertext, nil
}

func Decrypt(ciphertext, key, iv []byte) ([]byte, error) {
	// 创建加密算法 aes
	c, err := aes.NewCipher(key)
	if err != nil {
		log.Error("NewCipher(%d bytes) error:%s", len(key), err)
		return nil, err
	}
	// 解密字符串
	cfbdec := cipher.NewCFBDecrypter(c, iv)
	//存储明文
	plaintext := make([]byte, len(ciphertext))
	cfbdec.XORKeyStream(plaintext, ciphertext)
	log.Info("%x=>%s\n", ciphertext, plaintext)
	return plaintext, nil
}
